package gy.com.sansharescuesystem.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import gy.com.sansharescuesystem.R;
import gy.com.sansharescuesystem.adapter.RescueAdapter;
import gy.com.sansharescuesystem.base.BaseFragment;
import gy.com.sansharescuesystem.callback.AcyncCallBack;
import gy.com.sansharescuesystem.entity.RescueListResData;
import gy.com.sansharescuesystem.entity.RescueListResult;
import gy.com.sansharescuesystem.modle.QueryModel;
import gy.com.sansharescuesystem.modle.impl.QueryModelImpl;
import gy.com.sansharescuesystem.utils.Constant;
import gy.com.sansharescuesystem.utils.UIUtils;


public class RescueFragment extends BaseFragment {
    private PullToRefreshListView mListView;
    private RescueAdapter mRescueAdapter;
    private RescueListResult mRescueResp;
    private List<RescueListResData> mDataList = new ArrayList<>();
    private QueryModel model;
    private ProgressBar mPbLoading;
    private static final int QUERY_SUCCESS = 1;
    private static final int QUERY_ERROR = 2;
    private static final int REFRESH_QUERY_SUCCESS = 3;
    private static final int REFRESH_QUERY_FAILED = 4;
    private static final int FIRST_OR_REFRESH_DATA = 5;
    private static final int GET_NEXT_PAGE_DATA = 6;
    private Dialog mLoadingDialog;
    private int mCurrentPageIndex = 0;

    private int mPage = 1;
    private static final String TOTAL_SOS_MESSAGE = "total_sos_message";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case QUERY_SUCCESS:
                    if (msg.obj != null) {
                        mRescueResp = (RescueListResult) msg.obj;
                        List<RescueListResData> data = mRescueResp.getData();
                        if (mRescueResp.getFlag() != 0&&data.size()>0) {
                            if (msg.arg1 == FIRST_OR_REFRESH_DATA) {
                                mDataList.clear();
                                mDataList.addAll(data);
                                mCurrentPageIndex = 0;
                                //发送总条数广播
                                Intent intent = new Intent();
                                intent.setAction(TOTAL_SOS_MESSAGE);
                                intent.putExtra("total", mRescueResp.getTotal());
                                getActivity().sendBroadcast(intent);
                            } else if (msg.arg1 == GET_NEXT_PAGE_DATA) {
                                mCurrentPageIndex = mDataList.size()-1;
                                if(mPage==Integer.parseInt(mRescueResp.getCurrent())){
                                    if (data.size() != 0) {
                                        mDataList.addAll(data);
                                    } else {
                                        UIUtils.showToast(getActivity(), "没有更多数据");
                                    }
                                }else{
                                    UIUtils.showToast(getActivity(), "没有更多数据");
                                }
                            }
                        }else{
                            UIUtils.showToast(getActivity(),"查无数据");
                        }
                    }
                    mPbLoading.setVisibility(View.GONE);
                    mListView.onRefreshComplete();
                    showRescueList();
                    break;
                case QUERY_ERROR:
                    UIUtils.showToast(mActivity, "获取救援信息失败");
                    mListView.onRefreshComplete();
                    break;
                case REFRESH_QUERY_SUCCESS:
                    if (mLoadingDialog != null) {
                        mLoadingDialog.dismiss();
                    }
                    dealWithUpdate((RescueListResult) msg.obj);
                    break;
            }
        }
    };

    private void dealWithUpdate(RescueListResult obj) {
        if (obj != null && mRescueAdapter != null) {
            mDataList.clear();
            mDataList.addAll(obj.getData());
            mRescueAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected View onCreateView(LayoutInflater inflater) {

        View view = inflater.inflate(R.layout.fragment_rescue, null);
        //
        return view;
    }

    @Override
    protected void initView() {
        mListView = (PullToRefreshListView) findViewById(R.id.lv_expand);
        mPbLoading = (ProgressBar) findViewById(R.id.pb_loading_data);
    }

    @Override
    protected void setWidgetListener() {
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (mListView.isHeaderShown()) {
                    getDataByPage(FIRST_OR_REFRESH_DATA);
                } else if (mListView.isFooterShown()) {
                    getDataByPage(GET_NEXT_PAGE_DATA);
                }
            }
        });
    }

    @Override
    protected void initData() {
        getDataByPage(FIRST_OR_REFRESH_DATA);
    }

    private void getDataByPage(final int flag) {
        if (flag == FIRST_OR_REFRESH_DATA) {
            mPage = 1;
        } else if (flag == GET_NEXT_PAGE_DATA) {
            mPage = mPage + 1;
        }
        model = new QueryModelImpl();
        model.queryRescueInfo(new AcyncCallBack() {
            @Override
            public void onSuccess(Object resp) {
                Message msg = handler.obtainMessage();
                msg.what = QUERY_SUCCESS;
                msg.obj = resp;
                msg.arg1 = flag;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailed() {
                handler.sendEmptyMessage(QUERY_ERROR);
            }
        }, mPage);
    }

    private void showRescueList() {
        if (mRescueAdapter == null) {
            mRescueAdapter = new RescueAdapter(mActivity, mDataList, mListView);
        }
        mRescueAdapter.notifyDataSetChanged();
        mListView.setAdapter(mRescueAdapter);
        mListView.getRefreshableView().setSelection(mCurrentPageIndex);
    }

    @Override
    public void onPause() {
        super.onPause();
        Intent intent = new Intent(Constant.RESCUE_PAUSE);
        getActivity().sendBroadcast(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        Intent intent = new Intent(Constant.RESCUE_RESUME);
        getActivity().sendBroadcast(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
        Intent intent = new Intent(Constant.RESCUE_STOP);
        getActivity().sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(Constant.RESCUE_DESTROY);
        getActivity().sendBroadcast(intent);
    }
}
